package com.sz.common.base.dao.ext.impl;

import com.sz.common.base.dao.Dao;
import com.sz.common.base.dao.ext.ScriptDao;
import org.apache.ibatis.jdbc.ScriptRunner;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;

/**
 * Package: com.sz.common.base.dao.ext.impl <br>
 * Function: TODO: ADD FUNCTION <br>
 * Author: Charles. <br>
 * Date: 2017-04-06 15:53:00.
 */
@Service
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public class ScriptDaoSupport implements ScriptDao {

    @Autowired
    Dao dao;

    /**
     * @param file
     */
    @Override
    public void executeScript(String file) {
        if (file == null || file.length() == 0) {
            return;
        }
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(file);
        executeScript(inputStream);
    }

    /**
     * @param inputStream
     */
    @Override
    public void executeScript(InputStream inputStream) {
        if (inputStream == null) {
            return;
        }
        try {
            Reader reader = new InputStreamReader(inputStream, "UTF-8");
            ScriptRunner runner = new ScriptRunner(dao.getConnection());
            runner.setSendFullScript(true);
            runner.runScript(reader);
        } catch (UnsupportedEncodingException ex) {
            throw new RuntimeException(ex);
        }
    }
}
